const WebSocket = require('ws');
const axios = require('axios');

// 简化的宝石镶嵌功能测试
async function testGemSocketSimple() {
    console.log('🔧 开始简化宝石镶嵌功能测试...\n');

    let ws;
    let userId = null;
    let selectedCharacterId = null;

    try {
        // 步骤1: HTTP登录
        console.log('🔐 步骤1: HTTP登录...');
        const loginResponse = await axios.post('http://localhost:3000/user-service/user/login', {
            mobile: '17091271111',
            pwd: 'e10adc3949ba59abbe56e057f20f883e'
        });

        if (loginResponse.data.code === 0) {
            userId = loginResponse.data.data.userId;
            console.log(`✅ 登录成功: userId=${userId}`);
        } else {
            console.log('❌ 登录失败:', loginResponse.data);
            return;
        }

        // 步骤2: WebSocket连接
        console.log('\n🔌 步骤2: WebSocket连接...');
        const token = loginResponse.data.data.accessToken;
        ws = new WebSocket(`ws://localhost:3000/user-service/websocket?t=${token}`);

        await new Promise((resolve, reject) => {
            ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            ws.on('error', (error) => {
                console.log('❌ WebSocket连接失败:', error.message);
                reject(error);
            });
        });

        // 设置消息处理器
        let messageCount = 0;
        ws.on('message', (data) => {
            messageCount++;
            const message = JSON.parse(data.toString());
            console.log(`📨 收到消息 #${messageCount}:`, message);
        });

        // 步骤3: 查询角色列表
        console.log('\n📋 步骤3: 查询角色列表...');
        ws.send(JSON.stringify({ c: 3, d: {} }));

        // 等待角色列表响应
        await new Promise((resolve) => {
            const checkMessage = (data) => {
                const message = JSON.parse(data.toString());
                if (message.act_id === 3) {
                    console.log(`✅ 获取到${message.roleCount}个角色`);
                    selectedCharacterId = message.roleList[0].id;
                    console.log(`🎯 选择角色: ${message.roleList[0].name} (ID: ${selectedCharacterId})`);
                    resolve();
                }
            };

            ws.once('message', checkMessage);
        });

        // 步骤4: 选择角色
        console.log('\n🎯 步骤4: 选择角色...');
        ws.send(JSON.stringify({ c: 4, d: { id: selectedCharacterId } }));

        // 等待角色选择响应
        await new Promise((resolve) => {
            const checkMessage = (data) => {
                const message = JSON.parse(data.toString());
                if (message.act_id === 4) {
                    console.log('✅ 角色选择成功');
                    resolve();
                }
            };

            ws.once('message', checkMessage);
        });

        // 步骤5: 查询宝石背包
        console.log('\n💎 步骤5: 查询宝石背包...');
        ws.send(JSON.stringify({ c: 6034, d: { pageNum: 0 } }));

        // 等待宝石背包响应
        const gemListResponse = await new Promise((resolve) => {
            const checkMessage = (data) => {
                const message = JSON.parse(data.toString());
                if (message.act_id === 6034) {
                    console.log(`✅ 宝石背包查询成功，共${message.sum}个宝石`);
                    resolve(message);
                }
            };

            ws.once('message', checkMessage);
        });

        if (gemListResponse.list.length === 0) {
            console.log('⚠️  背包中没有宝石，无法测试镶嵌功能');
            return;
        }

        // 步骤6: 测试查询可镶嵌装备 (1090)
        console.log('\n🔍 步骤6: 测试查询可镶嵌装备(1090)...');
        const firstGem = gemListResponse.list[0];
        console.log(`🔧 测试宝石: ${firstGem.name} (ID: ${firstGem.id})`);

        ws.send(JSON.stringify({ c: 1090, d: { id: firstGem.id } }));

        // 等待可镶嵌装备响应
        const socketableEquipmentResponse = await new Promise((resolve) => {
            const checkMessage = (data) => {
                const message = JSON.parse(data.toString());
                if (message.act_id === 1090) {
                    console.log(`✅ 查询可镶嵌装备成功，找到${message.data.length}件装备`);
                    resolve(message);
                }
            };

            ws.once('message', checkMessage);
        });

        if (socketableEquipmentResponse.data.length > 0) {
            // 步骤7: 测试宝石镶嵌 (1092)
            console.log('\n⚡ 步骤7: 测试宝石镶嵌(1092)...');
            const firstEquipment = socketableEquipmentResponse.data[0];
            console.log(`🔧 测试装备: ${firstEquipment.name} (ID: ${firstEquipment.id})`);
            console.log(`💎 宝石槽位: ${firstEquipment.stoneStr}`);

            ws.send(JSON.stringify({
                c: 1092,
                d: {
                    id: firstGem.id,    // 宝石ID
                    aid: firstEquipment.id  // 装备ID
                }
            }));

            // 等待宝石镶嵌响应
            const socketGemResponse = await new Promise((resolve) => {
                const checkMessage = (data) => {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1092) {
                        if (message.code === 0) {
                            console.log('✅ 宝石镶嵌成功');
                            console.log('📝 镶嵌结果:', message.data);
                        } else {
                            console.log('❌ 宝石镶嵌失败:', message.msg);
                        }
                        resolve(message);
                    }
                };

                ws.once('message', checkMessage);
            });
        } else {
            console.log('⚠️  没有可镶嵌的装备');
        }

    } catch (error) {
        console.error('❌ 测试过程中发生错误:', error.message);
    } finally {
        // 关闭连接
        if (ws) {
            console.log('\n🔌 步骤8: 断开WebSocket连接...');
            ws.close();
            console.log('✅ 断开连接: 连接已断开');
        }
    }

    console.log('\n🎉 简化宝石镶嵌功能测试完成！');
}

// 运行测试
testGemSocketSimple().catch(console.error);
